﻿using EasyOAuth.Core.Web;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using MingHui.ShopExpress.Manage.API;

namespace EasyOAuth
{
    /// <summary>
    /// 自定义授权
    /// </summary>
    [OAuth]
    [ApiResultCustomFormat] //如果直接手动实现统一格式 这里可以注释掉
    [ApiController]
    public class OAuthController : ControllerBase
    {

    }

    /// <summary>
    /// 用户登录信息 
    /// </summary>
    public class UserSessionInfo
    {
        /// <summary>
        /// 用户ID
        /// </summary>
        public int Id { get; set; } = 0;

        /// <summary>
        /// 用户名称
        /// </summary>
        public string Name { get; set; } = string.Empty;
    }
    
    /// <summary>
    /// 接口结果重写
    /// </summary>
    //[AttributeUsage(AttributeTargets.Class)]
    public class ApiResultCustomFormatAttribute : Attribute, IResultFilter
    {
        /// <summary>
        /// 执行后
        /// </summary>
        /// <param name="context"></param>
        public void OnResultExecuted(ResultExecutedContext context)
        {


        }

        /// <summary>
        /// 执行前
        /// </summary>
        /// <param name="context"></param>
        public void OnResultExecuting(ResultExecutingContext context)
        {
            //忽略格式
            if (context.Filters.Contains(new IgnoreFormattingResultAttribute()))
            {
                return;
            }

            if (context.Result is ObjectResult result)
            {
                context.Result = new JsonResult(new ApiResult()
                {
                    Code = 0,
                    Data = result.Value ?? new object { },
                    Msg = "ok"
                });
            }
        }
    }

    /// <summary>
    /// 忽略格式
    /// </summary>
    public class IgnoreFormattingResultAttribute : Attribute, IFilterMetadata
    {

    }
    
}
 